<template>
  <div>
    <el-form-item
      v-if="activeData.ocrType !== undefined"
      :label="$t('formgen.ocrConfig.ocrType')"
    >
      <el-select
        size="default"
        v-model="activeData.ocrType"
        @change="handleOcrTypeChange"
      >
        <el-option
          :label="$t('formgen.ocrConfig.text')"
          value="GENERAL"
        />
        <el-option
          :label="$t('formgen.ocrConfig.idCard')"
          value="idCard"
        />
        <el-option
          :label="$t('formgen.ocrConfig.bankCard')"
          value="bankCard"
        />
        <el-option
          :label="$t('formgen.ocrConfig.businessLicense')"
          value="businessLicense"
        />
      </el-select>
      <el-button
        class="mt10"
        size="default"
        style="width: 100%"
        icon="ele-Edit"
        @click="handleOcrRule"
      >
        {{ $t("formgen.ocrConfig.setRule") }}
      </el-button>
    </el-form-item>
    <el-form-item
      v-if="activeData.options !== undefined && activeData.options.id_card_side"
      :label="$t('formgen.ocrConfig.idCardSide')"
    >
      <el-radio-group v-model="activeData.options.id_card_side">
        <el-radio-button value="front">
          {{ $t("formgen.ocrConfig.idCardSideFront") }}
        </el-radio-button>
        <el-radio-button value="back">{{ $t("formgen.ocrConfig.idCardSideBack") }}</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-dialog
      v-model="dialogVisible"
      :title="$t('formgen.ocrConfig.setRule')"
      width="40%"
    >
      <span class="text-danger">{{ $t("formgen.ocrConfig.desc") }}</span>
      <div class="mb10">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          {{ $t("formgen.ocrConfig.checkAll") }}
        </el-checkbox>
      </div>
      <div>
        <el-checkbox-group
          v-model="checkedFields"
          @change="handleCheckedFieldsChange"
        >
          <div
            v-for="key in Object.keys(getOcrFields(activeData.ocrType))"
            :key="key"
          >
            <el-checkbox
              :key="key"
              :label="key"
              :value="key"
            >
              <div class="m5">
                <el-tag>{{ getOcrFields(activeData.ocrType)[key]["label"] }}</el-tag>
                {{ $t("formgen.ocrConfig.saveTo") }}
                <el-tag v-if="Object.keys(activeData.fieldMapping)">
                  {{ getFormField(key) }}
                </el-tag>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            size="default"
            @click="dialogVisible = false"
          >
            {{ $t("formI18n.all.cancel") }}
          </el-button>
          <el-button
            size="default"
            type="primary"
            @click="handleCreateFields"
          >
            {{ $t("formgen.ocrConfig.createField") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineEmits } from "vue";
import { i18n } from "@/i18n";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash-es";
import {
  bankCardField,
  businessLicenseField,
  idCardBack,
  idCardFront
} from "@/views/formgen/components/FormDesign/ItemConfig/ocr/OcrConfig";
import { removeHtmlTag } from "@/views/formgen/utils";
import { formDesign } from "@/views/formgen/components/FormDesign/hooks/useFormDesign";

const emit = defineEmits(["add-fields"]);

const props = defineProps({
  formConf: {
    type: Object,
    default: () => {
      return {};
    }
  },
  activeData: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

const handleOcrTypeChange = (val: any) => {
  props.activeData.options = {};
  props.activeData.fieldMapping = {};
  if (val === "idCard") {
    props.activeData.options = {
      id_card_side: "front"
    };
  }
};

const dialogVisible = ref(false);

const checkAll = ref(false);
const isIndeterminate = ref(true);

const checkedFields = ref<any[]>([]);

const handleCheckAllChange = (val: boolean) => {
  checkedFields.value = val ? Object.keys(ocrFields.value[props.activeData.ocrType]) : [];
  isIndeterminate.value = false;
};

const handleCheckedFieldsChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === Object.keys(ocrFields.value[props.activeData.ocrType]).length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < Object.keys(ocrFields.value[props.activeData.ocrType]).length;
};

const { drawingList } = formDesign;

const ocrFields = ref<any>({
  GENERAL: {
    url: {
      type: "IMAGE_UPLOAD",
      label: i18n.global.t("formgen.ocrConfig.file")
    },
    ocrContent: {
      type: "INPUT",
      label: i18n.global.t("formgen.ocrConfig.ocrType")
    }
  },
  idCard: {},
  bankCard: bankCardField,
  businessLicense: businessLicenseField
});

const getFormField = (key: string) => {
  let fieldKey = "";
  if (props.activeData && props.activeData.fieldMapping && props.activeData.fieldMapping[key]) {
    fieldKey = props.activeData.fieldMapping[key];
  }
  const field = drawingList.value.find((item: any) => item.vModel == fieldKey);
  return field ? removeHtmlTag(field.config.label) : "";
};

const handleCreateFields = () => {
  if (!checkedFields.value.length) {
    ElMessage.warning("请选择要创建的字段");
    return;
  }
  dialogVisible.value = false;
  const obj = cloneDeep(ocrFields.value[props.activeData.ocrType]);
  // 只有选中的字段才保留
  Object.keys(obj).forEach(key => {
    if (!checkedFields.value.includes(key)) {
      delete obj[key];
    }
  });
  console.log(obj);
  emit("add-fields", obj);
};

const handleOcrRule = async () => {
  dialogVisible.value = true;
  if (props.activeData.fieldMapping == undefined) {
    props.activeData.fieldMapping = {};
  }
  if (props.activeData.options == undefined) {
    props.activeData.options = {};
  }
  if (props.activeData.ocrType === "idCard") {
    if (props.activeData?.options?.id_card_side == "front") {
      ocrFields.value["idCard"] = idCardFront;
    } else {
      ocrFields.value["idCard"] = idCardBack;
    }
  }
};

const getOcrFields = (key: string) => {
  return ocrFields.value[key];
};
</script>
